/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sampleServlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import sampleBean.CusSessionBeanRemote;
import sampleEntity.BookRoom;
import sampleEntity.Customers;
import sampleEntity.Room;

/**
 *
 * @author ASUS K43E
 */
public class Controller extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            Context context = new InitialContext();
            Object obj = context.lookup("remoteJNDI");
            CusSessionBeanRemote remote = (CusSessionBeanRemote) obj;
            String button = request.getParameter("btAction");
            HttpSession session = request.getSession();
            //login
            if (button.equals("Login")) {
                String errorLogin = "";
                String url = "login.jsp";
                String username = request.getParameter("txtUsername");
                String password = request.getParameter("txtPassword");

                if (username.length() == 0 || password.length() == 0) {
                    errorLogin = "Invalid uername or password!";
                } else {
                    boolean result = remote.checkLogin(username, password);
                    int role = 0;
                    int rank = 0;

                    if (result) {
                        role = remote.checkRole(username);
                        if (role == 1) {
                            url = "admin.jsp";
                        } else if (role == 2) {
                            url = "staff.jsp";
                            List pro = remote.productId();
                            session.setAttribute("PRODUCT", pro);
                            List room = remote.listRoom();
                            session.setAttribute("ROOMID", room);
                        } else if (role == 3) {
                            url = "member.jsp";
                            rank = remote.checkRank(username);
                            Customers cs = remote.findCus(username);

                            session.setAttribute("USERLIST", cs);
                            session.setAttribute("ISBLOCK", remote.checkBlock(username));
                            session.setAttribute("RANK", rank);
                        }
                        session.setAttribute("USER", username);
                    } else {
                        errorLogin = "Invalid uername or password!";
                    }
                }
                session.setAttribute("ERRORLOGIN", errorLogin);
                RequestDispatcher rd = request.getRequestDispatcher(url);
                rd.forward(request, response);
            } //logout
            else if (button.equals("logout")) {
                session.setAttribute("USER", "");
                response.sendRedirect("login.jsp");
            } //choose date for booking
            else if (button.equals("Choose")) {
                String username = request.getParameter("txtUsername");
                String dateString = request.getParameter("txtDate");
                String mess = "";
                //ko chon ngay
                if (dateString.length() == 0) {
                    mess = "Please choose a day!";
                }//co chon ngay
                else {
                    String pattern = "MM/dd/yyyy";
                    SimpleDateFormat format = new SimpleDateFormat(pattern);
                    Date date = new Date();

                    //check date
                    Date today = new Date();
                    Calendar c = Calendar.getInstance();

                    try {
                        today = format.parse(format.format(c.getTime()));
                        date = format.parse(dateString);
                    } catch (ParseException ex) {
                        Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
                    }

                    //choose past day
                    if (today.compareTo(date) > 0) {
                        mess = "You can't book for that day anymore. Please choose another day.";
                    }//choose present or future day
                    else {

                        //book phong roi
                        List bookRoom = remote.findBookRoom(username, date);

                        //chua book phong
                        if (bookRoom.isEmpty()) {
                            List bookRoomList = remote.showRoom(date);
                            List roomList = remote.showRoomList();
                            List goldList = remote.findGoldRoom();

                            BookRoom[] b = new BookRoom[bookRoomList.size()];
                            bookRoomList.toArray(b);
                            Room[] r = new Room[roomList.size()];
                            roomList.toArray(r);
                            Room[] gr = new Room[goldList.size()];
                            goldList.toArray(gr);

                            for (int i = 0; i < r.length; i++) {
                                for (int j = 0; j < b.length; j++) {
                                    if (r[i].getRoomId().equals(b[j].getBookRoomPK().getRoomId())) {
                                        roomList.remove(r[i]);
                                    }
                                }
                            }

                            for (int i = 0; i < gr.length; i++) {
                                for (int j = 0; j < b.length; j++) {
                                    if (gr[i].getRoomId().equals(b[j].getBookRoomPK().getRoomId())) {
                                        goldList.remove(gr[i]);
                                    }
                                }
                            }

                            session.setAttribute("ROOMLIST", roomList);
                            session.setAttribute("GOLDLIST", goldList);
                        }
                        session.setAttribute("BOOKROOM", bookRoom);
                    }
                }
                request.setAttribute("MESS", mess);
                RequestDispatcher rd = request.getRequestDispatcher("bookPage.jsp");
                rd.forward(request, response);
            } //book a room
            else if (button.equals("Book")) {
                String username = request.getParameter("txtUsername");
                String dateString = request.getParameter("txtDate");
                String pattern = "MM/dd/yyyy";
                SimpleDateFormat format = new SimpleDateFormat(pattern);
                Date date = new Date();
                try {
                    date = format.parse(dateString);
                } catch (ParseException ex) {
                    Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
                }
                String roomId = request.getParameter("rdo");
                String roomName = request.getParameter("txtRoomName");
                String message1 = "";
                String message2 = "";
                if (roomId == null) {
                    message1 = "Please choose a room";
                } else {
                    boolean result = remote.addNewBook(roomId, date, username);
                    if (result) {
                        message2 = "You have booked room " + roomName + ".<br/>Thanks for booking. See you soon.";
                    } else {
                        message2 = "Error";
                    }
                }
                request.setAttribute("MESSAGE1", message1);
                request.setAttribute("MESSAGE2", message2);
                RequestDispatcher rd = request.getRequestDispatcher("bookPage.jsp");
                rd.forward(request, response);
            } //cancel booking
            else if (button.equals("Yes, please cancel.")) {
                String username = request.getParameter("txtUser");
                String dateString = request.getParameter("txtDate");
                String pattern = "MM/dd/yyyy";
                SimpleDateFormat format = new SimpleDateFormat(pattern);
                Date date = new Date();
                try {
                    date = format.parse(dateString);
                } catch (ParseException ex) {
                    Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
                }
                String roomId = request.getParameter("txtBookRoom");

                boolean result = remote.cancelBooking(roomId, date);
                String url = "bookPage.jsp";
                if (result) {
                    url = "Controller?btAction=Choose&txtUsername=" + username + "&txtDate=" + dateString;
                }
                RequestDispatcher rd = request.getRequestDispatcher(url);
                rd.forward(request, response);
            } else if (button.equals("History")) {// view history cua customers
                String username = request.getParameter("username");

                List result = remote.viewHistory(username);
                request.setAttribute("HISLIST", result);
                RequestDispatcher rd = request.getRequestDispatcher("history.jsp");
                rd.forward(request, response);
            } else if (button.equals("Save Changes")) {// edit info cua member
                String username = request.getParameter("txtUserName");
                String job = request.getParameter("txtJob");
                String add = request.getParameter("txtAddress");
                String phone = request.getParameter("txtTelephone");
                String bankAcc = request.getParameter("txtBank");
                String bankName = request.getParameter("txtBankName");
                int flag = 0;
                //validate bank account
                String messBacc = "";
                if (bankAcc.length() == 0) {
                    messBacc = "Bank account is required!";
                    flag = 1;
                }

                //validate bank name
                String messbName = "";
                if (bankName.length() == 0) {
                    messbName = "Bank name is required!";
                    flag = 1;
                }

                String url = "editInfo.jsp";
                if (flag == 0) {
                    boolean result = remote.editInfo(username, job, add, phone, bankAcc, bankName);
                    if (result) {
                        Customers cs = remote.findCus(username);
                        session.setAttribute("USERLIST", cs);
                    }
                }

                request.setAttribute("MESSBACC", messBacc);
                request.setAttribute("MESSBANAME", messbName);
                RequestDispatcher rd = request.getRequestDispatcher(url);
                rd.forward(request, response);
            } else if (button.equals("Save Password")) {//change pass
                String username = request.getParameter("txtUsername");
                String oldPass = request.getParameter("txtcusOldPass");
                String newPass = request.getParameter("txtcusNewPass");
                String conPass = request.getParameter("txtconNewPass");
                int flag = 0;
                String url = "changePass.jsp";
                //validate old password
                String messOP = "";
                if (oldPass.length() == 0) {
                    messOP = "Old password is required!";
                    flag = 1;
                } else if (!remote.checkPass(username, oldPass)) {
                    messOP = "Old password is incorrect!";
                    flag = 1;
                }

                //validate new password
                String messNP = "";
                if (newPass.length() == 0) {
                    messNP = "New password is required!";
                    flag = 1;
                }

                //validate confirm new password
                String messCNP = "";
                if (conPass.length() == 0) {
                    messCNP = "Confirm new password is required!";
                    flag = 1;
                } else if (!newPass.equals(conPass)) {
                    messCNP = "Confirm new password does not match new password!";
                    flag = 1;
                }

                if (flag == 0) {
                    boolean result = remote.changePass(username, newPass);
                    if (result) {
                        session.setAttribute("USER", "");
                        url = "login.jsp";
                    }
                }

                request.setAttribute("MESSOP", messOP);
                request.setAttribute("MESSNP", messNP);
                request.setAttribute("MESSCNP", messCNP);
                RequestDispatcher rd = request.getRequestDispatcher(url);
                rd.forward(request, response);
            }//register new account
            else if (button.equals("Register")) {
                String username = request.getParameter("txtUsername");
                String phone = request.getParameter("txtTelephone");
                if (phone.length() == 0) {
                    phone = "";
                }
                String password = request.getParameter("txtPassword");
                String dateString = request.getParameter("txtDate");
                String pattern = "MM/dd/yyyy";
                SimpleDateFormat format = new SimpleDateFormat(pattern);
                Date dateOfBirth = new Date();
                try {
                    dateOfBirth = format.parse(dateString);
                } catch (ParseException ex) {
                    Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
                }
                String conPass = request.getParameter("txtconPassword");
                String id = request.getParameter("txtIdentity");
                String fullname = request.getParameter("txtFullname");
                String bankAcc = request.getParameter("txtBankAccount");
                String gender = request.getParameter("ddlGender");
                String bankName = request.getParameter("txtBankName");
                String email = request.getParameter("txtEmail");
                String job = request.getParameter("txtJob");
                if (job.length() == 0) {
                    job = "";
                }
                String address = request.getParameter("txtAddress");
                if (address.length() == 0) {
                    address = "";
                }
                String verification = request.getParameter("txtVer");

                int flag = 0;
                String url = "register.jsp";

                //validate username
                String messUser = "";
                if (username.length() == 0) {
                    flag = 1;
                    messUser = "Username is required!";
                } else if (remote.checkUser(username)) {
                    flag = 1;
                    messUser = "Username is existed";
                } else if (username.length() >= 30) {
                    flag = 1;
                    messUser = "Too long!!!";
                }

                //validate password
                String messPass = "";
                if (password.length() == 0) {
                    flag = 1;
                    messPass = "Password is required!";
                } else if (password.length() >= 30) {
                    flag = 1;
                    messPass = "Too long!!!";
                }

                //validate confirm password
                String messCNP = "";
                if (conPass.length() == 0) {
                    messCNP = "Confirm password is required!";
                    flag = 1;
                } else if (!password.equals(conPass)) {
                    messCNP = "Confirm password does not match password!";
                    flag = 1;
                }

                //validate fullname
                String messFull = "";
                if (fullname.length() == 0) {
                    messFull = "Full name is required!";
                    flag = 1;
                }

                //validate bank account
                String messBacc = "";
                if (bankAcc.length() == 0) {
                    messBacc = "Bank account is required!";
                    flag = 1;
                }

                //validate bank name
                String messbName = "";
                if (bankName.length() == 0) {
                    messbName = "Bank name is required!";
                    flag = 1;
                }

                //validate email
                String messEmail = "";
                if (email.length() == 0) {
                    messEmail = "Email is required!";
                    flag = 1;
                } else if (remote.checkEmail(email)) {
                    messEmail = "Email is existed!";
                    flag = 1;
                }

                //validate id
                String messId = "";
                if (id.length() == 0) {
                    messId = "ID is required!";
                    flag = 1;
                } else if (remote.checkID(id)) {
                    messId = "ID is existed!";
                    flag = 1;
                }

                //verification
                String messVer = "";
                if (verification.length() == 0) {
                    messVer = "Verification is required!";
                    flag = 1;
                }

                //validate dob
                String messDob = "";
                if (dateString.length() == 0) {
                    messDob = "Date of birth is required!";
                    flag = 1;
                }

                if (flag == 0) {
                    boolean result = remote.register(username, password, fullname, address, phone, email);
                    if (result) {
                        url = "registerSuccess.jsp";
                    }
                }

                request.setAttribute("MESSCNP", messCNP);
                request.setAttribute("MESSUSER", messUser);
                request.setAttribute("MESSPASS", messPass);
                request.setAttribute("MESSFULL", messFull);
                request.setAttribute("MESSBACC", messBacc);
                request.setAttribute("MESSEMAIL", messEmail);
                request.setAttribute("MESSID", messId);
                request.setAttribute("MESSBANAME", messbName);
                request.setAttribute("MESSVER", messVer);
                request.setAttribute("MESSDOB", messDob);
                request.setAttribute("NEW", username);
                RequestDispatcher rd = request.getRequestDispatcher(url);
                rd.forward(request, response);
            }//reset password
            else if (button.equals("Get password")) {
                String email = request.getParameter("txtEmail");
                String verification = request.getParameter("txtVer");
                String url = "resetPassword.jsp";

                //verification
                String messVer = "";
                if (verification.length() == 0) {
                    messVer = "Verification is required!";
                }

                //validate email
                String messEmail = "Email is not existed!";
                if (email.length() == 0) {
                    messEmail = "Email is required!";
                } else if (remote.checkEmail(email)) {
                    messEmail = "";
                    url = "resetSuccess.jsp";
                }

                request.setAttribute("MESSEMAIL", messEmail);
                request.setAttribute("MESSVER", messVer);
                RequestDispatcher rd = request.getRequestDispatcher(url);
                rd.forward(request, response);
            }
        } catch (NullPointerException ex) {
            Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NamingException ex) {
            Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
